package com.ziiwee.reduce.rest.jpa;

import com.fasterxml.jackson.core.type.TypeReference;
import com.ziiwee.reduce.rest.Resource;
import com.ziiwee.reduce.rest.ResourceService;
import com.ziiwee.reduce.rest.ResourceServiceException;
import com.ziiwee.reduce.rest.condition.Condition;
import com.ziiwee.reduce.rest.utils.JsonUtil;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import java.util.Map;

public class JpaResourceService<T extends Resource<ID>, ID> implements ResourceService<T, ID> {

    private final Class<T> entityClass;
    private final JpaDataAccessor jpaDataAccessor;

    public JpaResourceService(Class<T> entityClass, JpaDataAccessor jpaDataAccessor) {
        this.jpaDataAccessor = jpaDataAccessor;
        this.entityClass = entityClass;
    }

    @Override
    public Page<T> findAll(Pageable pageable, Condition condition) {
        return jpaDataAccessor.findPage(entityClass, pageable, condition);
    }

    @Override
    public T findOne(ID id) {
        return jpaDataAccessor.findOne(entityClass, id).orElse(null);
    }

    @Override
    public T create(T t) {
        return jpaDataAccessor.save(t);
    }

    @Override
    public T update(ID id, Map<String, Object> parameters) {
        //
        T saved = findOne(id);
        saved = handleUpdate(saved, parameters);
        return jpaDataAccessor.save(saved);
    }

    private T handleUpdate(T saved, Map<String, Object> parameters) {
//        T entity;
//        try {
//            String json = JsonUtil.write(parameters);
//            entity = JsonUtil.read(json, entityClass);
//        } catch (Exception e) {
//            throw new RuntimeException("无法解析的数据：");
//        }

        Map<String, Object> savedMap = JsonUtil.readByRef(JsonUtil.write(saved), new TypeReference<Map<String, Object>>() {
        });
        if (savedMap == null) {
            throw new ResourceServiceException("无法解析的数据");
        }
        savedMap.putAll(parameters);

        return JsonUtil.read(JsonUtil.write(savedMap), entityClass);


//        for (Object key : parameters.keySet()) {
//            String name = key.toString();
//            Field field = BeanUtil.getField(entityClass, name);
//            if (field == null) {
//                throw new ConditionParserException("字段不存在：" + name);
//            }
//            Class<?> type = field.getType();
//            Object castValue = JsonUtil.castValue(type, parameters.get(name));
////            Object value = BeanUtil.getValue(entity, name);
//
//        }
    }

    @Override
    public void delete(ID id) {
        jpaDataAccessor.deleteById(entityClass, id);
    }
}
